package fun.sanguo.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Base64;

/**
 * 类型转换工具类
 *
 * @author ZYP
 * @date 2022-07-20
 */
public class TypeConvertUtils {

    /**
     * 字节数组转base64
     *
     * @param bytes
     * @return
     */
    public static String byteArrayToBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * base64转字节数组
     *
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] base64ToByteArray(String base64) throws Exception {
        return Base64.getDecoder().decode(base64);
    }

    /**
     * 字节转16进制字符串
     *
     * @param b
     * @return
     */
    public static String byteToHexString(byte b) {
        String[] hexChars = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexChars[d1] + hexChars[d2];
    }

    /**
     * 字节数组转16进制字符串
     *
     * @param bytes
     * @return
     */
    public static String byteArrayToHexString(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append(byteToHexString(bytes[i]));
        }
        return stringBuffer.toString();
    }

    /**
     * 16进制字符转字节
     *
     * @param c
     * @return
     */
    public static byte hexCharToByte(char c) {
        return (byte) "0123456789abcdef".indexOf(c);
    }

    /**
     * 16进制字符串转字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToByteArray(String hexString) {
        if (StringUtils.isEmpty(hexString)) {
            return null;
        }
        // 转换为小写
        hexString = hexString.trim().toLowerCase();
        // 转换后数组长度
        int length = hexString.length() / 2;
        byte[] d = new byte[length];
        // 遍历转换为字节并放入数组
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (hexCharToByte(hexString.charAt(pos)) << 4 | hexCharToByte(hexString.charAt(pos + 1)));
        }
        return d;
    }
}